import router from "@/router";
import store from "@/store";
import ACCESS_ENUM from "@/access/accessEnum";
import checkAccess from "@/access/checkAccess";
import message from "@arco-design/web-vue/es/message";
import { useRoute } from "vue-router";

/**
 * 路由权限拦截
 */
router.beforeEach(async (to, from, next) => {
  if (to.meta?.access === "canAdmin") {
    if (store.state.user.loginUser?.role !== "admin") {
      next("/noAuth");
      message.error("无权限");
      return;
    }
  }

  //如果未登录或者登录用户没有权限(如果尝试登录的话会有userRole这个属性为ACCESS_ENUM.NOT_LOGIN,没登录到则为空)
  if (!store.state.user.loginUser || !store.state.user.loginUser.userRole) {
    //加上await 是为了等用户登录成功后再执行后续的代码,防止异步情况下登录用户信息未获取到
    await store.dispatch("user/getLoginUser");
  }
  const needAccess = to.meta?.access ?? ACCESS_ENUM.NOT_LOGIN;
  //当页面必须需要登录时
  if (needAccess !== ACCESS_ENUM.NOT_LOGIN) {
    //如果没登陆或者没有访问权限的时候，跳转到登陆界面，传递原来需要跳转的页面地址
    if (
      !store.state.user.loginUser?.userRole ||
      store.state.user.loginUser?.userRole === ACCESS_ENUM.NOT_LOGIN
    ) {
      message.warning("当前页面需要登录才能访问");
      next(`/user/login?redirect=${to.fullPath}`);
      return;
    }
    //如果登录了，但是权限不足跳转到无权限界面
    if (!checkAccess(store.state.user.loginUser, needAccess as string)) {
      next("/noAuth");
    }
  }
  next();
});
